package me.techbird.nve.dao.impl;

import me.techbird.nve.dao.QuestionDao;
import me.techbird.nve.domain.ExamOptions;
import me.techbird.nve.domain.ExamQuestion;
import me.techbird.nve.domain.ExamTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.*;

public class QuestionDaoImpl implements QuestionDao {
    private JdbcTemplate template = new JdbcTemplate(me.techbird.express.util.JDBCUtils.getDataSource());
    @Override
    public List<ExamQuestion> findQuestion() {
        int bounds = findCount();

        //创建一个产生随机数的对象
        Random r = new Random();
        //创建一个存储随机数的集合
        Vector<Integer> v = new Vector<Integer>();
        //定义一个统计变量
        int count = 0;
        while(count < 5){
            int number = r.nextInt(bounds)+1;
            //判断number是否在集合中存在
            if(!v.contains(number)){
                //不在集合中，就添加
                v.add(number);
                count++;
            }
        }

        List<ExamQuestion> questions = new ArrayList<>();
        for (int id : v) {
            String sql = "select * from tab_question where qid = ?";
            System.out.println(sql+id);
            ExamQuestion qs =  template.queryForObject(sql, new BeanPropertyRowMapper<ExamQuestion>(ExamQuestion.class),id);
            questions.add(qs);
        }
        return questions;
    }

    @Override
    public int addTest(ExamTest test) {
        String sql = "insert into tab_test(uid,course,score,create_time) values(?,?,?,?)";
        return template.update(sql, test.getUid(),test.getCourse(),test.getScore(),new Date());
    }

    @Override
    public int findCount() {
        String countSql = "select count(*) from tab_question";
        int count = template.queryForObject(countSql, Integer.class);
        return count;
    }

    @Override
    public ExamOptions findOption(int oid) {
        String sql = "select * from tab_option where oid = ?";
        ExamOptions options = template.queryForObject(sql, new BeanPropertyRowMapper<ExamOptions>(ExamOptions.class), oid);
        return options;
    }
}
